<template>
	<view class="video_upload">
		<view class="image_area u-flex u-flex-wrap u-flex-between" style="align-items: center;" >

			<view @click="showImgSheet(index)" v-for="(item, index) in imgList"
				 :class="imgList.length>1?'movemargin':''">
				<image mode="aspectFill" :src="$url(item.src)" :key="index"  :style="[wrapStyle]"></image>
				<view class="progress_bg u-flex u-row-center u-col-center" :style="{height: item.progress + '%'}"
					v-if="item.progress < 100">
					<text>{{item.progress}}%</text>
				</view>
			</view>
			<template v-if="mode === 'all'">
				<view class="choose_area " @click="show = true" :class="bgUrl?'':'change'" :style="[wrapStyle]">
					<view class="middle">
						<u-icon :name="icon" :size="iconsize" color="#ccc"></u-icon>

						<view v-if="icontxt" class="icontxt">{{icontxt}}</view>
					</view>
				</view>
			</template>
			<template v-if="mode === 'image' && imgList.length < defaultLength">
				<view class="choose_area " @click="show = true" :class="bgUrl?'':'change'" :style="[wrapStyle]">
					<view class="middle">
						<u-icon :name="icon" :size="iconsize" color="#ccc"></u-icon>
						<view v-if="icontxt" class="icontxt">{{icontxt}}</view>
					</view>
				</view>
			</template>
			<template v-if="mode === 'video' && !videoSrc">
				<view class="choose_area " @click="show = true">
					<view class="middle">
						<u-icon :name="icon" :size="iconsize" color="#ccc"></u-icon>

						<view v-if="icontxt" class="icontxt">{{icontxt}}</view>
					</view>
				</view>
			</template>
			<video v-if="videoSrc" :src="videoSrc" :controls="videoFullScreen" :show-center-play-btn="videoFullScreen"
				id="prew_video" @fullscreenchange="videoScreenChange">


				<view class="video_view u-flex u-row-center u-col-center" v-if="!videoFullScreen">
					<u-icon name="play-circle-fill" size="80" color="#e2e2e2" @click="videoSheetShow=true"></u-icon>

				</view>
			</video>
		</view>
		<!-- <view class="preview_video" @click="videoSheetShow = true" v-show="poster" v-if="videoSrc">
			<u-image mode="aspectFit" width="300rpx" height="400rpx" :src="videoInfo.poster"></u-image>
			<view class="progress_bg u-flex u-row-center u-col-center" :style="{height: videoInfo.progress + '%'}">
				<u-icon name="play-circle-fill" size="80" color="#e2e2e2" v-if="videoInfo.progress >= 100"></u-icon>
				<text v-else>{{videoInfo.progress}}%</text>
			</view>
		</view> -->

		<u-action-sheet :list="list" v-model="show" @click="chooseType"></u-action-sheet>

		<u-action-sheet :list="imgSheetList" v-model="imgSheetShow" @click="imgSheetChoose"></u-action-sheet>
		<u-action-sheet :list="videoSheetList" v-model="videoSheetShow" @click="videoSheetChoose"></u-action-sheet>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import baseUrl from '../common/baseUrl.js';
	export default {
		props: {
			type: {
				type: String,
				default: ''
			},
			bgUrl: {
				type: String,
				default: ''
			},
			icon: {
				type: String,
				default: 'camera'
			},
			iconsize: {
				type: [String, Number],
				default: 60
			},
			icontxt: {
				type: String,
				default: ""
			},
			afterLoadUrl: {
				type: String,
				default: ""
			},
			width: {
				type: [String, Number],
				default: 250
			},
			height: {
				type: [String, Number],
				default: 250
			},
			borderRadius: {
				type: [String, Number],
				default: ""
			},

			customDir: {
				type: String,
				default: ""
			},
			defaultLength: {
				type: [String, Number],
				default: 9
			},
			destWidth: {
				type: [String, Number],
				default: ""
			},
			destHeight: {
				type: [String, Number],
				default: ""
			},
			// 裁剪框宽度，高等于宽，单位px
			rectWidth: {
				type: [String, Number],
				default: ""
			},
			rectHeight: {
				type: [String, Number],
				default: ""
			},
			//当前使用裁剪的类型，避免监听函数多次执行
			cutType: {
				type: [String],
				default: ""
			}
		},
		computed: {
			wrapStyle() {
				let style = {};

				return style;
			}
		},
		data() {
			return {
				imagesurl: baseUrl.imageUrl,
				show: false,
				list: [
					//#ifdef MP
					{
						text: "拍摄照片",
						id: 0
					},
					{
						text: "拍摄视频",
						id: 1
					},
					//#endif
					{
						text: "从手机相册选择照片",
						id: 2
					},
					{
						text: "从手机相册选择视频(5分钟内视频)",
						id: 3
					},
				],
				imgSheetShow: false,
				videoFullScreen: false,
				chooseImgIndex: null, //选中的图片index
				videoSheetList: [{
						text: "预览"
					},
					{
						text: "删除",
						color: "#e93b3c"
					},
				],
				videoSheetShow: false,
				imgSheetList: [{
						text: "预览"
					},
					{
						text: "删除",
						color: "#e93b3c"
					},
				],
				imgList: [],
				afterUploadImgList: [],
				videoSrc: "",
				videoInfo: {
					width: 0,
					height: 0
				},
				ossConfig: {},
				videoContext: null,
				mode: 'all' //image 图片  可以选择9张    video 只能选择一个  all 全部
			}
		},
		watch: {
			afterLoadUrl: {
				immediate: true,
				handler(v) {
					console.log(v, 333)
					if (v) {
						let arr = v.split(","),
							_arr = [];
						this.afterUploadImgList = arr
						arr.forEach(item => {
							_arr.push({
								src: item,
								progress: 100
							})
						})
						this.imgList = _arr
					}
				}
			},
			mode: {
				immediate: true,
				handler(v) {
					if (v === 'image') {
						this.list = this.list.filter(item => item.id === 0 || item.id === 2)
					}
					if (v === 'video') {
						this.list = this.list.filter(item => item.id === 1 || item.id === 3)
					}
				}
			},
			type: {
				immediate: true,
				handler(v) {
					this.mode = v || "all"
					if (v === 'image') {
						this.list = this.list.filter(item => item.id === 0 || item.id === 2)
					}
					if (v === 'video') {
						this.list = this.list.filter(item => item.id === 1 || item.id === 3)
					}
				}
			},
			imgList(v) {
				if (v.length === 0 && !this.type) {
					this.list = [
						//#ifdef MP
						{
							text: "拍摄照片",
							id: 0
						},
						{
							text: "拍摄视频",
							id: 1
						},
						//#endif
						{
							text: "从手机相册选择照片",
							id: 2
						},
						{
							text: "从手机相册选择视频(5分钟内视频)",
							id: 3
						},
					]
				}
			},
			videoSrc(v) {
				if (!v && !this.type) {
					this.list = [
						//#ifdef MP
						{
							text: "拍摄照片",
							id: 0
						},
						{
							text: "拍摄视频",
							id: 1
						},
						//#endif
						{
							text: "从手机相册选择照片",
							id: 2
						},
						{
							text: "从手机相册选择视频(5分钟内视频)",
							id: 3
						},
					]
				}
			}
		},
		computed: {
			wrapStyle() {
				let style = {};
				// 通过调用addUnit()方法，如果有单位，如百分比，px单位等，直接返回，如果是纯粹的数值，则加上rpx单位
				style.width = this.$u.addUnit(this.width);
				style.height = this.$u.addUnit(this.height);
		
				style.backgroundImage = 'url('+this.imagesurl+''+this.bgUrl+')'
				
				style.borderRadius = this.$u.addUnit(this.borderRadius);
				
				console.log(style)
				return style;
			}
		},
		onReady(res) {


		},
		created() {

			this.videoContext = uni.createVideoContext('prew_video', this);

			uni.$on('uAvatarCropper', path => {
				try {
					this.imgList.push({
						src: path,
						progress: 0
					})
					this.uploadImage(path);
				} catch (err) {
					this.$u.toast("上传失败" + err)
				}
			})
		},
		methods: {
			...mapMutations(["SET_GLOBAL_CUT_TYPE"]),

			//图片选择完成之后
			afterChooseImage(path) {
				if (this.destWidth) {

					this.$u.route({
						// 关于此路径，请见下方"注意事项"
						url: '/uview-ui/components/u-avatar-cropper/u-avatar-cropper',
						// 内部已设置以下默认参数值，可不传这些参数
						params: {
							// 输出图片宽度，高等于宽，单位px
							destWidth: this.destWidth,
							destHeight: this.destHeight,
							// 裁剪框宽度，高等于宽，单位px
							rectWidth: this.rectWidth || this.destWidth,
							rectHeight: this.rectHeight || this.destHeight,
							// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
							fileType: 'jpg',
							defaultSrc: path
						}
					})
					return
				}
				try {
					this.imgList.push({
						src: path,
						progress: 0
					})
					this.uploadImage(path);
				} catch (err) {
					this.$u.toast("上传失败" + err)
				}
			},
			showImgSheet(index) {
				this.imgSheetShow = true;
				this.chooseImgIndex = index;
			},
			imgSheetChoose(index) {
				if (index === 0) {
					this.previewImg();
				}
				if (index === 1) {
					this.imgList.splice(this.chooseImgIndex, 1)
					this.afterUploadImgList.splice(this.chooseImgIndex, 1)
				}
			},
			videoSheetChoose(index) {
				if (index === 0) {
					this.previewVideo();
				}
				if (index === 1) {
					this.$emit("deleteVideo", this.videoSrc)
					this.videoSrc = ""
				}
			},
			previewImg() {
				uni.previewImage({
					urls: this.afterUploadImgList,
					current: this.afterUploadImgList[0],
					success() {

					},
					fail() {

					}
				})
			},
			previewVideo(e) {
				var videoContext = this.videoContext;
				videoContext.seek(0);
				videoContext.play();
				videoContext.requestFullScreen();
			},
			videoScreenChange(e) {
				var status = e.detail.fullScreen;
				this.videoFullScreen = status;
				if (!status) {
					this.videoContext.pause();
				}
			},
			/**
			 * 获取阿里OSS签名相关
			 */
			// getAliOssAssign() {
			// 	this.$u.api.getOssSign({loading: true, dir: this.customDir}).then(res => {
			// 		this.ossConfig = res.data
			// 	}).catch(err => {
			// 		console.error(err)
			// 	})
			// },

			chooseType(index) {
				let currentId = this.list[index].id


				switch (currentId) {
					case 0:
						this.chooseImageCamera();
						break;
					case 1:
						this.chooseVideoCamera();
						break;
					case 2:
						this.chooseImage();
						break;
					case 3:
						this.chooseVideo();
						break;
				}
			},
			/**
			 * 选择图片
			 */
			chooseImage() {
				uni.chooseImage({
					sourceType: ["album"],
					sizeType: ['compressed'],
					count: this.defaultLength - this.imgList.length,
					success: res => {
						this.mode = "image"
						res.tempFilePaths.forEach(item => {
							this.afterChooseImage(item)
							// this.imgList.push({
							// 	src: item,
							// 	progress: 0
							// })
							// this.uploadImage(item)
						})
					},
					fail: err => {
						console.error(err)
					}
				})
			},
			/**
			 * 选择视频
			 */
			chooseVideo() {
				uni.chooseVideo({
					sourceType: ["album"],
					sizeType: ['compressed'],
					count: 1,
					maxDuration: 60,
					success: res => {
						console.warn(res)
						this.videoInfo = {
							width: res.width,
							height: res.height
						}
						this.mode = "video";
						this.uploadImage(res.tempFilePath)
						console.error(res, "选择视频")
					},
					fail: err => {
						console.error(err)
					}
				})
			},
			/**
			 * 选择拍照
			 */
			chooseImageCamera() {
				uni.chooseMedia({
					count: 1,
					mediaType: ["image"],
					sizeType: ['compressed'],
					sourceType: ["camera"],
					success: res => {
						this.mode = "image";
						let tempFilePath = res.tempFiles[0].tempFilePath;
						this.afterChooseImage(tempFilePath);
						// this.uploadImage(tempFilePath)
						// this.imgList.push({
						// 	src: tempFilePath,
						// 	progress: 0
						// })
					},
					fail: err => {
						console.error(err)
					}
				})
			},
			/**
			 * 选择录制
			 */
			chooseVideoCamera() {
				uni.chooseMedia({
					count: 1,
					sizeType: ['compressed'],
					mediaType: ["video"],
					sourceType: ["camera"],
					maxDuration: 60,
					success: res => {

						this.mode = "video"
						this.videoInfo = {
							width: res.tempFiles[0].width,
							height: res.tempFiles[0].height
						}
						this.uploadImage(res.tempFiles[0].tempFilePath);
						console.error(res, "录制视频");
					},
					fail: err => {
						console.error(err)
					}
				})
			},
			getSuffix(fileName) {
				var pos = fileName.lastIndexOf(".");
				var suffix = "";
				if (pos != -1) {
					suffix = fileName.substring(pos);
				}
				return suffix;
			},
			uploadImage(url) {
				return new Promise(async (resolve, reject) => {
					uni.showLoading({
						title: '上传中...'
					})
					let path = ""
					if (this.mode === "video") {
						try {
							// path = await this.compressVideo(url)
							path = url
						} catch (e) {
							path = url;
						}
					}
					if (this.mode === "image") {
						// path = await this.compressImage(url)
						path = url
					}

					// const filename = new Date().getTime() + this.getSuffix(url)

					// console.log(filename,111)
					const uploadTask = uni.uploadFile({
						url: baseUrl.url + '/api/index/uploadImage',
						filePath: url,
						name: 'file',
						success: (res) => {
							var Data = JSON.parse(res.data)
							var fileUrl = Data.data[0].host + Data.data[0].src;
							if (this.mode === "image") {
								this.afterUploadImgList.push(fileUrl);
							}
							if (this.mode === "video") {
								this.videoSrc = fileUrl;
								this.$emit("videoUploaded", fileUrl);
							}


						},
						fail: err => {
							reject('上传失败');
						},
						complete: res => {

							uni.hideLoading()
						}
					})


					/**
					 * 记录图片上传对应的进度
					 */
					this.mode === "image" && this.imgList.forEach((item, index) => {
						if (item.src == url) {
							uploadTask.onProgressUpdate((res) => {
								this.onProgressUpdate(res, index)
							})
						}
					})
				})
			},
			onProgressUpdate(e, index) {
				this.$set(this.imgList, index, {
					src: this.imgList[index].src,
					progress: e.progress
				})
			},
			compressImage(url) {
				return new Promise((resolve, reject) => {
					//#ifdef MP
					uni.compressImage({
						src: url,
						quality: 50,
						success: res => {
							resolve(res.tempFilePath);
						},
						fail: err => {
							reject(err);
						}
					})
					//#endif
					//#ifdef H5
					resolve(url)
					//#endif
				})
			},
			compressVideo(url) {
				return new Promise((resolve, reject) => {
					uni.compressVideo({
						quality: 'high',
						src: url,
						success: res => {
							resolve(res.tempFilePath);
						},
						fail: err => {
							reject(err);
						}
					})
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.image_area {
		// width: 720rpx;

		// margin-left: 30rpx;
		>view {
			position: relative;
			// width: 200rpx;
			// height: 200rpx;
			transition: all linear 0.2s;
			margin-bottom: 40rpx;
			margin-right: 20rpx;
		}
	}

	.preview_video {
		width: 300rpx;
		height: 400rpx;
		position: relative;
	}

	.progress_bg {
		position: absolute;
		width: 100%;
		height: 0rpx;
		background-color: rgba(0, 0, 0, 0.3);
		bottom: 0;
		left: 0;
		color: #fff;
		z-index: 2;
	}

	video {
		width: 300rpx;
		position: relative;
	}

	.video_view {
		position: absolute;
		left: 0;
		top: 0%;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.video_upload {
		width: 100%;
		margin-right: 30rpx;


		.choose_area {

			transition: all linear 0.2s;
			text-align: center;
			position: relative;
			margin-bottom: 40rpx;
			background-size: cover;
			background-repeat: no-repeat;


		}

		.change {
			background-color: #eee;
		}

		.middle {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);

			.icontxt {
				color: #999;
			}
		}
	}
	
	

	.movemargin{
		margin-right: 30rpx;
		margin-bottom: 30rpx;
	}
</style>
